<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="18">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="标题" />
            </el-form-item>
            <el-form-item label="摘要" prop="digest">
              <el-input
                v-model="formData.digest"
                type="textarea"
                placeholder="摘要"
              />
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <editor
                v-model="formData.content"
                style="height: calc(80vh - 180px); z-index: 999"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="分类" prop="category_id">
              <el-cascader
                v-model="formData.category_id"
                :options="options"
                :props="{ checkStrictly: true }"
                @change="cascaderCheck"
                clearable
              />
            </el-form-item>
            <el-form-item label="封面图" prop="cover_img">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
              >
                <img
                  v-if="formData.cover_img"
                  :src="formData.cover_img"
                  class="avatar"
                  alt=""
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="formData.author" placeholder="作者" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                controls-position="right"
                :min="0"
                style="width: 100px"
              />
            </el-form-item>
            <el-form-item label="类型" prop="is_release">
              <el-radio-group v-model="formData.is_release">
                <el-radio-button label="发布" value="1" />
                <el-radio-button label="草稿" value="0" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="formData.type">
                <el-radio-button label="文章" value="1" />
                <el-radio-button label="页面" value="2" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="is_hid">
              <el-radio-group v-model="formData.is_hid">
                <el-radio :value="0">正常</el-radio>
                <el-radio :value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">保 存</el-button>
              <el-button @click="goBack">取 消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ArticleAdd",
  inheritAttrs: false,
});
import Editor from "@/components/WangEditor/index.vue";
import { addArticle, updateArticle, getArticleForm } from "@/api/article";
import { getOptions } from "@/api/category";
import { CategoryOptions } from "@/api/category/types";
import { ArticleForm } from "@/api/article/types";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { LocationQueryValue, useRoute } from "vue-router";
import { ElLoading } from "element-plus";

const options = ref<CategoryOptions[]>(); // 下拉数据源
const userFormRef = ref(ElForm); // 表单
const formData = reactive<ArticleForm>({
  // 表单数据
  is_hid: 0,
  is_release: 0,
  type: 1,
  sort: 0,
});
// 校验规则
const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  cover_img: [{ required: true, message: "封面图不能为空", trigger: "blur" }],
  category_id: [{ required: true, message: "分类必选", trigger: "blur" }],
});
const uploadUrl = ref(
  import.meta.env.VITE_APP_API_URL + "/admin/article/upload"
);
const headers = ref({
  Authorization: localStorage.getItem("accessToken"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  formData.cover_img = response.data.url;
};
const imageType = ["image/jpeg", "image/png", "image/jpg"];

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!imageType.includes(rawFile.type)) {
    ElMessage.error("图片格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不超过 2MB!");
    return false;
  }
  return true;
};

function cascaderCheck(data: any) {
  if (data.length > 0) {
    formData.category_id = data[data.length - 1];
  } else {
    formData.category_id = 0;
  }
}

function goBack() {
  window.history.back();
}
function getFormData(id: string | LocationQueryValue[]) {
  getArticleForm(id).then(({ data }) => {
    Object.assign(formData, { ...data });
  });
}

async function loadOptions() {
  getOptions().then((response) => {
    options.value = response.data;
  });
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    const router = useRouter();
    if (valid) {
      const ids = formData.id;
      const loading = ElLoading.service({
        lock: true,
        text: ids ? "修改提交中..." : "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (ids) {
        updateArticle(formData)
          .then(() => {
            // router.push("/cms/article");
            loading.close();
            ElMessage.success("修改成功");
          })
          .finally();
      } else {
        addArticle(formData)
          .then(() => {
            // router.push("/cms/article");
            loading.close();
            ElMessage.success("新增成功");
          })
          .finally();
      }
    }
  });
}, 3000);

onMounted(() => {
  const route = useRoute();
  if (route.query.id) {
    getFormData(parseInt(route.query.id));
  }
  loadOptions();
});
</script>
<style>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  cursor: pointer;
  display: inline-block;
  overflow: hidden;
  text-align: center;
  height: 5rem;
  line-height: 5rem;
}
.avatar {
  width: 100%;
  height: 5rem;
  line-height: 5rem;
  border-radius: 6px;
}
</style>
